package com.military.controller;

import com.military.pojo.Result;
import com.military.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("military")
@Slf4j
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 本地文件上传
     * @param file
     * @return
     * @throws IOException
     */
//    @PostMapping("/upload")
//    public Result upload(MultipartFile file) throws IOException {
//        log.info("文件上传:{}",  file);
//
//        //获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//
//        //先获取扩展名
//        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //重新生成文件名
//        String newFileName = UUID.randomUUID().toString() + extName;
//
//        //保存在本地
//        file.transferTo(new File("E:/" + newFileName));
//        return Result.success();
//
//    }

    /**
     * 阿里云文件上传
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件上传:{}",  file.getOriginalFilename());//文件原始名称
        //将文件交给oss存储
        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
        log.info("文件上传完成，上传路径:{}",  url);
        return Result.success(url);
    }
}
